<?php

namespace maotool\util;

use maotool\core\request\RequestUtil;
use maotool\http\HttpUtil;

class WebHookUtil
{

    public static function send($url, $data, $secret = null)
    {
        if ($secret !== null) {
            $timestamp = strval(round(microtime(true) * 1000));
            $string_to_sign = $timestamp . "\n" . $secret;
            $hmac_code = hash_hmac('sha256', $string_to_sign, $secret, true);
            $sign = urlencode(base64_encode($hmac_code));
            $request = HttpUtil::post(UrlUtil::addParams($url, ['timestamp' => $timestamp, 'sign' => $sign]), $data);
        } else {
            $request = HttpUtil::post($url, $data);
        }
        $request->execute();
    }

    public static function sendText($url, $content, $secret = null)
    {
        $data = [
            'msgtype' => 'text',
            'text' => [
                'content' => $content
            ]
        ];
        self::send($url, $data, $secret);
    }

    public static function sendMarkdown($url, $title, $text, $secret = null)
    {
        $data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'title' => $title,
                'text' => $text
            ]
        ];
        self::send($url, $data, $secret);
    }

    public static function sendLink($url, $title, $text, $link, $secret = null)
    {
        $data = [
            'msgtype' => 'link',
            'link' => [
                'title' => $title,
                'text' => $text,
                'messageUrl' => $link
            ]
        ];
        self::send($url, $data, $secret);
    }

    public static function sendImage($url, $base64, $secret = null)
    {
        $data = [
            'msgtype' => 'image',
            'image' => [
                'base64' => $base64
            ]
        ];
        self::send($url, $data, $secret);
    }

}